package com.ruibang.glass.quality.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.quality.constant.QualityErrorCode;
import com.ruibang.glass.quality.domain.req.QualityStrengthReq;
import com.ruibang.glass.quality.entity.QualityStrength;
import com.ruibang.glass.quality.feign.FileApi;
import com.ruibang.glass.quality.mapper.QualityStrengthMapper;
import com.ruibang.glass.quality.service.QualityStrengthService;
import com.ruibang.glass.quality.util.PoiUtils;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import com.teaming.cloud.framework2.common.pojo.PageRequest;
import com.teaming.cloud.framework2.common.pojo.PageResult;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 成品强度信息 服务实现类
 * </p>
 *
 * @author wujie
 * @since 2024-03-20
 */
@Service
public class QualityStrengthServiceImpl extends ServiceImpl<QualityStrengthMapper, QualityStrength> implements QualityStrengthService {

    private static final Integer INT_ELEVEN = 11;
    private static final Integer INT_TWELVE = 12;
    private static final Integer INT_FIFTEEN = 15;
    private static final Integer INT_NINETEEN = 19;


    @Autowired
    private FileApi fileApi;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Override
    public void saveInfo(QualityStrength qualityStrength) {
        this.save(qualityStrength);
        //更新文件对应业务Id
        if(CollectionUtils.isNotEmpty(qualityStrength.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(qualityStrength.getFileIds());
            fileBusiness.setBusinessId(qualityStrength.getStrengthId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public void updateInfo(QualityStrength qualityStrength) {
        //更新文件信息
        if(CollectionUtils.isNotEmpty(qualityStrength.getDeleteFileIds())){
            fileApi.deleteByFileIds(qualityStrength.getDeleteFileIds());
        }
        //新增文件
        if(CollectionUtils.isNotEmpty(qualityStrength.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(qualityStrength.getStrengthId());
            fileBusiness.setFileIds(qualityStrength.getFileIds());
            fileApi.updateBusinessById(fileBusiness);
        }

        this.updateById(qualityStrength);
    }

    @Override
    public List<QualityStrength> queryQualityStrength(QualityStrengthReq strengthReq) {
        final LambdaQueryWrapper<QualityStrength> lambda = new QueryWrapper<QualityStrength>().lambda();
        this.buildCondition(lambda,strengthReq);
        List<QualityStrength> list = this.list(lambda);
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        for (QualityStrength qs : list) {
            if(userMap!=null){
                qs.setUserName(userMap.get(qs.getUserId())==null?"":userMap.get(qs.getUserId()).toString());
            }
        }
        return list;
    }

    @Override
    public QualityStrength importStrength(MultipartFile file) {
        QualityStrength strength = new QualityStrength();
        if(file == null) return strength;
        String fileName = file.getOriginalFilename();
        if(StringUtils.isNotBlank(fileName)){
            int dotIndex = fileName.lastIndexOf('.');
            String suffix = fileName.substring(dotIndex + 1);
            if(StringUtils.isNotBlank(suffix)){
                if(Constants.FILE_TYPE_XLSM.equals(suffix)
                        ||Constants.FILE_TYPE_XLS.equals(suffix)
                        ||Constants.FILE_TYPE_XLSX.equals(suffix)){
                    InputStream inputStream = null;
                    Workbook workbook = null;
                    try {
                        inputStream = file.getInputStream();
                        workbook = WorkbookFactory.create(inputStream);
                        int sheetCount = workbook.getNumberOfSheets();
                        if(sheetCount >= CommonConstant.ONE_INT){
                            Sheet sheet = workbook.getSheetAt(CommonConstant.ZERO_INT);
                            Row row1 = sheet.getRow(CommonConstant.TWO_INT);
                            Cell cell1 = row1.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell1)){
                                strength.setGlassModel(cell1.getStringCellValue());//玻璃型号
                            }

                            Row row2 = sheet.getRow(CommonConstant.TWO_INT);
                            Cell cell2 = row2.getCell(CommonConstant.FIVE_INT);
                            if(!PoiUtils.isEmptyCell(cell2)) {
                                LocalDate measureDate = cell2.getLocalDateTimeCellValue().toLocalDate();
                                if(measureDate!=null){
                                    strength.setMeasureDate(measureDate);
                                }
                            }

                            Cell cell3 = row2.getCell(CommonConstant.SEVEN_INT);
                            if(!PoiUtils.isEmptyCell(cell3)) {
                                LocalDateTime dateTime = cell3.getLocalDateTimeCellValue();
                                strength.setCheckTime(dateTime.getHour()+":"+dateTime.getMinute()+":"+dateTime.getSecond());
                            }


                            Cell cell4 = row2.getCell(CommonConstant.NINE_INT);
                            if(!PoiUtils.isEmptyCell(cell4)) {
                                strength.setGlassId(cell4.getStringCellValue());
                            }


                            try {
                                Cell cell5 = row2.getCell(INT_FIFTEEN);
                                if (!PoiUtils.isEmptyCell(cell5)) {
                                    String name = cell5.getStringCellValue();
                                    if (StringUtils.isNotBlank(name)) {
                                        strength.setProductLineName(name);
                                        Map<Object, Object> productMap = redisService.hmget(RedisKey.PRODUCT_LINE_GROUP_TYPE);
                                        if (productMap != null) {
                                            Map<String, String> productNameMap = new HashMap<>();
                                            productMap.forEach((k, v) -> {
                                                if (v != null && StringUtils.isNotBlank(v.toString())) {
                                                    productNameMap.put(v.toString(), k.toString());
                                                }
                                            });
                                            strength.setProductLine(productNameMap.get(name));
                                        }
                                    }

                                }
                            } catch (Exception e) {
                                throw new ServiceException(QualityErrorCode.WRITE_PRODUCTION_LINE.getCode(), QualityErrorCode.WRITE_PRODUCTION_LINE.getMsg());
                            }



                            Cell cell6 = row2.getCell(INT_NINETEEN);
                            if(!PoiUtils.isEmptyCell(cell6)) {
                                String userName = cell6.getStringCellValue();
                                if(StringUtils.isNotBlank(userName)){
                                    Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
                                    if(!userMap.isEmpty()){
                                        Map<String,String> userNameMap = new HashMap<>();
                                        userMap.forEach((k,v)->{
                                            if(v!=null&&StringUtils.isNotBlank(v.toString())){
                                                userNameMap.put(v.toString(),k.toString());
                                            }
                                        });
                                        strength.setUserId(userNameMap.get(userName));
                                    }
                                }
                            }


                            Row row12 = sheet.getRow(INT_TWELVE);
                            Cell cell7 = row12.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell7)) {
                                strength.setDamage1h1((float)cell7.getNumericCellValue());
                            }

                            Cell cell8 = row12.getCell(CommonConstant.TWO_INT);
                            if(!PoiUtils.isEmptyCell(cell8)) {
                                strength.setDamage1h2((float)cell8.getNumericCellValue());
                            }

                            Cell cell9 = row12.getCell(CommonConstant.THREE_INT);
                            if(!PoiUtils.isEmptyCell(cell9)) {
                                strength.setDamage1h3((float)cell9.getNumericCellValue());
                            }

                            Cell cell10 = row12.getCell(CommonConstant.FOUR_INT);
                            if(!PoiUtils.isEmptyCell(cell10)) {
                                strength.setDamage2h1((float)cell10.getNumericCellValue());
                            }

                            Cell cell11 = row12.getCell(CommonConstant.FIVE_INT);
                            if(!PoiUtils.isEmptyCell(cell11)) {
                                strength.setDamage2h2((float)cell11.getNumericCellValue());
                            }

                            Cell cell12 = row12.getCell(CommonConstant.SIX_INT);
                            if(!PoiUtils.isEmptyCell(cell12)) {
                                strength.setDamage2h3((float)cell12.getNumericCellValue());
                            }

                            Cell cell13 = row12.getCell(CommonConstant.SEVEN_INT);
                            if(!PoiUtils.isEmptyCell(cell13)) {
                                strength.setDamage3h1((float)cell13.getNumericCellValue());
                            }

                            Cell cell14 = row12.getCell(CommonConstant.EIGHT_INT);
                            if(!PoiUtils.isEmptyCell(cell14)) {
                                strength.setDamage3h2((float)cell14.getNumericCellValue());
                            }

                            Cell cell15 = row12.getCell(CommonConstant.NINE_INT);
                            if(!PoiUtils.isEmptyCell(cell15)) {
                                strength.setDamage3h3((float)cell15.getNumericCellValue());
                            }

                            Cell cell16 = row12.getCell(CommonConstant.TEN_INT);
                            if(!PoiUtils.isEmptyCell(cell16)) {
                                strength.setDamage4h1((float)cell16.getNumericCellValue());
                            }

                            Cell cell17 = row12.getCell(INT_ELEVEN);
                            if(!PoiUtils.isEmptyCell(cell17)) {
                                strength.setDamage4h2((float)cell17.getNumericCellValue());
                            }

                            Cell cell18 = row12.getCell(INT_TWELVE);
                            if(!PoiUtils.isEmptyCell(cell18)) {
                                strength.setDamage4h3((float)cell18.getNumericCellValue());
                            }

                            float average1h = 0.0f;
                            float average2h = 0.0f;
                            float average3h = 0.0f;
                            float average4h = 0.0f;

                            if(strength.getDamage1h1()>0){
                                strength.setFace1h1(strength.getDamage1h1() * 25 / 3.332f);
                                average1h = average1h + strength.getFace1h1();
                            }
                            if(strength.getDamage1h2()>0){
                                strength.setFace1h2(strength.getDamage1h2() * 25 / 3.332f);
                                average1h = average1h + strength.getFace1h2();
                            }
                            if(strength.getDamage1h3()>0){
                                strength.setFace1h3(strength.getDamage1h3() * 25 / 3.332f);
                                average1h = average1h + strength.getFace1h3();
                            }
                            if(strength.getDamage2h1()>0){
                                strength.setFace2h1(strength.getDamage2h1() * 25 / 3.332f);
                                average2h = average2h + strength.getFace2h1();
                            }
                            if(strength.getDamage2h2()>0){
                                strength.setFace2h2(strength.getDamage2h2() * 25 / 3.332f);
                                average2h = average2h + strength.getFace2h2();
                            }
                            if(strength.getDamage2h3()>0){
                                strength.setFace2h3(strength.getDamage2h3() * 25 / 3.332f);
                                average2h = average2h + strength.getFace2h3();
                            }
                            if(strength.getDamage3h1()>0){
                                strength.setFace3h1(strength.getDamage3h1() * 25 / 3.332f);
                                average3h = average3h + strength.getFace3h1();
                            }
                            if(strength.getDamage3h2()>0){
                                strength.setFace3h2(strength.getDamage3h2() * 25 / 3.332f);
                                average3h = average3h + strength.getFace3h2();
                            }
                            if(strength.getDamage3h3()>0){
                                strength.setFace3h3(strength.getDamage3h3() * 25 / 3.332f);
                                average3h = average3h + strength.getFace3h3();
                            }
                            if(strength.getDamage4h1()>0){
                                strength.setFace4h1(strength.getDamage4h1() * 25 / 3.332f);
                                average4h = average4h + strength.getFace4h1();
                            }
                            if(strength.getDamage4h2()>0){
                                strength.setFace4h2(strength.getDamage4h2() * 25 / 3.332f);
                                average4h = average4h + strength.getFace4h2();
                            }
                            if(strength.getDamage4h3()>0){
                                strength.setFace4h3(strength.getDamage4h3() * 25 / 3.332f);
                                average4h = average4h + strength.getFace4h3();
                            }

                            DecimalFormat decimalFormat = new DecimalFormat("#.00");

                            if(average1h>0){
                                strength.setAverage1h(Float.valueOf(decimalFormat.format(average1h/3)));
                            }
                            if(average2h>0){
                                strength.setAverage2h(Float.valueOf(decimalFormat.format(average2h/3)));
                            }
                            if(average3h>0){
                                strength.setAverage3h(Float.valueOf(decimalFormat.format(average3h/3)));
                            }
                            if(average4h>0){
                                strength.setAverage4h(Float.valueOf(decimalFormat.format(average4h/3)));
                            }
                            float grandAverage = strength.getAverage1h() + strength.getAverage2h() + strength.getAverage3h() + strength.getAverage4h();
                            if(grandAverage>0){
                                strength.setGrandAverage(Float.valueOf(decimalFormat.format(grandAverage/4)));
                            }
                        }

                    } catch (Exception e) {
                        log.error("执行流操作异常:"+e.getMessage());
                        throw new ServiceException(QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getCode(),QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getMsg());
                    }finally {
                        try {
                            if(inputStream!=null){
                                inputStream.close();
                            }
                            if(workbook!=null){
                                workbook.close();
                            }
                        } catch (IOException e) {
                            log.error("流关闭异常:"+e.getMessage());
                        }
                    }
                }
            }
        }

        ResultBody<String> resultBody = fileApi.uploadFile(file);
        if(resultBody!=null&&StringUtils.isNotBlank(resultBody.getData())){
            strength.setFileIds(Arrays.asList(resultBody.getData()));
        }

        return strength;
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(QualityStrength::getStrengthId, id).set(QualityStrength::getIsDelete, CommonConstant.ONE_STR).update();
    }

    @Override
    public PageResult<QualityStrength> queryPage(PageRequest<QualityStrengthReq> pageRequest) {
        final QualityStrengthReq param = pageRequest.getParam();
        final LambdaQueryWrapper<QualityStrength> lambda = new QueryWrapper<QualityStrength>().lambda();
        this.buildCondition(lambda,param);
        final IPage<QualityStrength> page = this.page(new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize()), lambda);
        if(page!=null&& CollectionUtils.isNotEmpty(page.getRecords())){
            List<String> ids = page.getRecords().stream().map(c->c.getStrengthId()).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(ids);
            Map<String,List<String>> fileMap = null;
            if(resultBody!=null&& com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(resultBody.getData())){
                fileMap = resultBody.getData().stream().collect(Collectors.toMap(f->f.getBusinessId(), f->f.getFileIds(),(f1, f2)->f1));
            }

            Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);

            for (QualityStrength record : page.getRecords()) {
                if(fileMap!=null){
                    record.setFileIds(fileMap.get(record.getStrengthId()));
                }

                if(userMap!=null){
                    record.setUserName(userMap.get(record.getUserId())==null?"":userMap.get(record.getUserId()).toString());
                }
            }
        }

        PageResult<QualityStrength> pr = new PageResult(page);
        return pr;
    }

    /**
     * 构造查询条件
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<QualityStrength> lambda, QualityStrengthReq param){
        lambda.eq(QualityStrength::getIsDelete, CommonConstant.ZERO_STR);
        if(null == param) return;
        if(StringUtils.isNotBlank(param.getStrengthId())){
            lambda.eq(QualityStrength::getStrengthId, param.getStrengthId());
        }
        if(StringUtils.isNotBlank(param.getGlassId())){
            lambda.eq(QualityStrength::getGlassId, param.getGlassId());
        }
        if(StringUtils.isNotBlank(param.getGlassModel())){
            lambda.eq(QualityStrength::getGlassModel, param.getGlassModel());
        }
        if(param.getMeasureStartDate()!=null&&param.getMeasureEndDate()!=null){
            lambda.ge(QualityStrength::getMeasureDate, param.getMeasureStartDate());
            lambda.le(QualityStrength::getMeasureDate, param.getMeasureEndDate());
        }
        if(StringUtils.isNotBlank(param.getCheckTime())){
            lambda.eq(QualityStrength::getCheckTime, param.getCheckTime());
        }
        if(StringUtils.isNotBlank(param.getProductLine())){
            lambda.eq(QualityStrength::getProductLine, param.getProductLine());
        }
        if(StringUtils.isNotBlank(param.getUserId())){
            lambda.eq(QualityStrength::getUserId, param.getUserId());
        }
        if(StringUtils.isNotBlank(param.getDecide())){
            lambda.eq(QualityStrength::getDecide, param.getDecide());
        }
        lambda.orderBy(true,false, QualityStrength::getMeasureDate);
    }
}
